<template>
  <!-- 条件节点 -->
  <div class="ep-node-condition">
    <div v-if="!props.node.isLastCondition">
      {{view}}
    </div>
    <div v-else>
      其他条件进入此流程
    </div>
  </div>

</template>

<script setup name="ConditionNode">
import {computed, getCurrentInstance, inject} from "vue";
import {KEY_PROCESS_CTRL, KEY_PROCESS_DATA, KEY_VALIDATOR} from "../../config/keys"
import {operatorMap} from "../../config/conditionOperator";

const props = defineProps({
  tempNodeId: { // 临时节点ID
    type: String
  },
  node: { // 传入的流程配置数据
    type: Object,
    default: {}
  }
});

const { proxy } = getCurrentInstance();

// 获取流程数据
const processData = inject(KEY_PROCESS_DATA)
const processCtrl = inject(KEY_PROCESS_CTRL)
// 获取流程验证器实例
const validator = inject(KEY_VALIDATOR)

// 注册验证器
validator.register(props.tempNodeId, () => {
  // 删除无效的条件
  // removeInvalidCondition()

  let valid = true;
  if (!props.node.isLastCondition) {
    if (props.node.config.conditions == null || props.node.config.conditions.length === 0) {
      valid = false
    }
  }

  return {
    "valid": valid,
    "message": "请设置条件"
  }
})

/**
 * 删除无效的条件（在表单设计器中被删除的字段）
 */
function removeInvalidCondition() {
  if (props.node.config.conditions) {
    let tmpConditions = []
    props.node.config.conditions.forEach(group => {
      if (group) {
        let newGroup = group.filter(condition => isInvalidCondition(condition.name))
        if (newGroup && newGroup.length > 0) {
          tmpConditions.push(newGroup)
        }
      }
    })
    props.node.config.conditions = tmpConditions
  }

}

/**
 * 是否为无效字段
 * @param name
 */
function isInvalidCondition(name) {
  let isInvalid = true
  let formFields = processCtrl.getFormFields()
  if (formFields) {
    formFields.forEach(field => {
      if (field.isCondition && field.name === name) {
        isInvalid = false
      }
    })
  }
  return isInvalid
}

const view = computed(()=> {
  let text = ""
  if (props.node.config.conditions) {
    props.node.config.conditions.forEach(group => {
      if (group) {
        group.forEach(condition => {
          text += condition.label + ";"
        })
      }
    })
  }


  if (text == null || text === "") {
    text = "请设置条件"
  }
  return text
})
</script>

<style lang="less" scoped>
.ep-node-condition {

}
</style>
